package com.lovo.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lovo.commom.WebRemote.IWebProductRemote;
import com.lovo.commom.psc.IPscOrderInfoRemote;
import com.lovo.commom.util.ConstantUtil;
import com.lovo.sys.bean.*;
import com.lovo.sys.mapper.*;
import com.lovo.sys.service.IProductService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
public class ProductServiceImpl implements IProductService {
    @Autowired
    private IProductMapper productMapper;
    @Autowired
    private IWebProductRemote webProductRemote;
    @Autowired
    private IProductInfoMapper productInfoMapper;
    @Autowired
    private IOrderInfoMapper orderInfoMapper;
    @Autowired
    private ISupplyProductMapper supplyProductMapper;
    @Autowired
    private IInventoryRecordsMapper iInventoryRecordsMapper;
    @Autowired
    private IPscOrderInfoRemote pscOrderInfoRemote;
    @Autowired
    private ISupplyMapper supplyMapper;
    @Autowired
    private ISupplyInfoMapper supplyInfoMapper;

    @Override
    public List<ProductBean> findByProductStatus() {
        List<ProductBean> list = productMapper.findAll();
        List<ProductBean> all = list;
        if (all != null) {
            for (ProductBean p : all) {
                p.setStatus(3);
                productMapper.updateById(p);
            }
        }
        return list;
    }

    @Override
    public IPage<ProductBean> findAll(int pageNO) {
        QueryWrapper<ProductBean> qw = new QueryWrapper<>();
        qw.eq("p_status", 1);
        return productMapper.selectPage(new Page<>(pageNO, ConstantUtil.SIZE), qw);
    }

    /**
     * 下架
     *
     * @param productName
     */
    @Override
    public void updateStatusToDown(String productName) {
        //根据商品名查看
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("p_productName", productName);
        ProductBean product = productMapper.selectOne(qw);
        //修改状态为  3-已下架
        product.setStatus(3);
        productMapper.updateById(product);
        //调用前端接口 修改前端库存表状态为下架
        webProductRemote.updateProductStatus(productName, 4);
    }

    /**
     * 上架
     *
     * @param productName 商品名
     */
    @Override
    public void updateStatus(String productName) {
        QueryWrapper<ProductBean> qw = new QueryWrapper<>();
        qw.eq("p_productName", productName);
        ProductBean productBean = productMapper.selectOne(qw);
        productBean.setStatus(2);
        productMapper.updateById(productBean);
        //调用前端接口 修改前端库存表状态为上架
        webProductRemote.updateProductStatus(productName, 3);
    }

    /**
     * 审核不通过,商品状态改为2--已拉取
     *
     * @param productName 商品名
     */
    @Override
    public void updateStatu(String productName) {
        QueryWrapper<ProductBean> qw = new QueryWrapper<>();
        qw.eq("p_productName", productName);
        ProductBean productBean = productMapper.selectOne(qw);
        productBean.setStatus(3);
        productMapper.updateById(productBean);
        //调用前端接口 修改前端库存表状态为审核不通过
        webProductRemote.updateProductStatus(productName, 2);
    }

    @Override
    public boolean updateProductStatus(String productName, int status) {
        try {

            QueryWrapper<ProductBean> qw = new QueryWrapper<>();
            qw.eq("p_productName", productName);
            ProductBean productBean = productMapper.selectOne(qw);
            productBean.setStatus(status);
            productMapper.updateById(productBean);
            return true;

        } catch (Exception e) {

            throw new RuntimeException();
        }

    }

    @Override
    public IPage<ProductBean> findListedProduct(int pageNO, String productType, int status) {
        QueryWrapper qw = new QueryWrapper<>();
        //已上架状态
        if (!"".equals(status)) {
            qw.eq("p_status", status);
        }
        if (!"".equals(productType) && productType != null) {
            qw.eq("p_type", productType);
        }
        return productMapper.selectPage(new Page<>(pageNO, ConstantUtil.SIZE), qw);
    }


    //发送给审核的采购提醒
    @Override

    @Scheduled(cron = "0 15 10 ? * *")
    public void remindToBuy() {
        List<ProductBean> productList = productMapper.selectList(null);
        for (int i = 0; i < productList.size(); i++) {
            //库存小于阈值，且不为预售商品的，可以发送采购提醒
            if (productList.get(i).getNum() <= productList.get(i).getBootomNum()
                    && productList.get(i).getIsPromotion() != 3) {
                //发送采购申请

            }
        }
    }


    //查看所有商品
    @Override
    public IPage<ProductBean> findAllProduct(int pageNO) {
        return productMapper.selectPage(new Page<>(pageNO, ConstantUtil.SIZE), null);
    }

    //查看商品明细
    @Override
    public List<ProductInfoBean> findByProduct(String productName) {
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("pi_productName", productName);
        return productInfoMapper.selectList(qw);
    }

    @Override
    public List<String> findAllType() {
        return productMapper.findAllType();
    }


    @Override
    public void backMoneyAndProduct(String productName, String specs, int num) {
        //修改product表
        QueryWrapper<ProductBean> qw = new QueryWrapper<>();
        qw.eq("p_productName", productName);
        ProductBean product = productMapper.selectOne(qw);
        product.setNum(product.getNum() + num);
        productMapper.updateById(product);
        //修改库存明细
        QueryWrapper<ProductInfoBean> qw2 = new QueryWrapper<>();
        qw2.eq("pi_specs", productName);
        //商品名
        qw2.eq("pi_productName", specs);
        ProductInfoBean productInfo = productInfoMapper.selectOne(qw2);
        productInfo.setInventory(productInfo.getInventory() + num);
        productInfoMapper.updateById(productInfo);

        //修改前端的商品库存 --- 远程接口


    }

    @Override
    public boolean updateProductInfoPrice(String obj) {
        try {
            ProductBean productBean = JSONObject.parseObject(obj, ProductBean.class);
            QueryWrapper<ProductBean> qw = new QueryWrapper<>();
            qw.eq("p_productName", productBean.getProductName());
            ProductBean product = productMapper.selectOne(qw);
            product.setStatus(1);
            productMapper.updateById(product);
            for (ProductInfoBean pi : productBean.getProductInfoList()) {
                QueryWrapper<ProductInfoBean> qw1 = new QueryWrapper<>();
                qw1.eq("pi_productName", productBean.getProductName());
                qw1.eq("pi_specs", pi.getSpecs());
                ProductInfoBean infoBean = productInfoMapper.selectOne(qw1);
                infoBean.setPrice(pi.getPrice());
                productInfoMapper.updateById(infoBean);
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    @Override
    public void addSnowId(String productName, String snowId) {
        QueryWrapper<ProductBean> qw = new QueryWrapper<>();
        qw.eq("p_productName", productName);
        ProductBean product = productMapper.selectOne(qw);
        product.setSnowId(snowId);
        productMapper.updateById(product);
    }

    //监听供应商订单批次MQ
//    @RabbitListener(queues = "")
    public void addOrderInfo(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, String json) {
        if (StringUtils.hasLength(json)) {
            OrderInfoBean orderInfo = JSONObject.parseObject(json, OrderInfoBean.class);
            orderInfoMapper.insert(orderInfo);
        }
    }

    @Override
    public void inKu(String idNum) {
        //查询idNum订单批次号的供货批次对象
        QueryWrapper qw3 = new QueryWrapper<>();
        qw3.eq("oi_idNum", idNum);
        OrderInfoBean orderInfo = orderInfoMapper.selectOne(qw3);
        System.out.println("orderInfo 状态为" + orderInfo.getOrderStatus());
        //判断该批次是否【已入库】
        if (orderInfo.getOrderStatus() != 1) {
            //根据批次号查询 供货批次表-供货商品表-供货商品明细表 三连
            //得到该批次的所有供货商品（包括供货商品明细）
            List<SupplyProductBean> supplyProductList = supplyProductMapper.findByPiciIdNum(idNum);

            //修改库存(商品库存表、商品明细表)
            for (int i = 0; i < supplyProductList.size(); i++) {
                //修改商品表库存数量
                QueryWrapper<ProductBean> qw = new QueryWrapper<>();
                qw.eq("p_productName", supplyProductList.get(i).getProductName());
                ProductBean product = productMapper.selectOne(qw);
                if (product != null) {
                    //修改该商品的库存数量
                    product.setNum(product.getNum() + supplyProductList.get(i).getNum());
                    productMapper.updateById(product);

                } else {
                    //添加新商品
                    SupplyProductBean supplyProduct = supplyProductList.get(i);
                    //商品名
                    product = new ProductBean();
                    product.setProductName(supplyProduct.getProductName());
                    //商品类型
                    product.setType(supplyProduct.getType());
                    //库存
                    product.setNum(supplyProduct.getNum());
                    //采购价
                    product.setPrice(supplyProduct.getBuyPrice());
                    productMapper.insert(product);
                }
                //遍历供货商品里的供货商品明细集合，修改商品明细表里的库存

                //当前遍历的第i个供货商品的供货商品明细集合
                List<SupplyInfoBean> supplyInfoList = supplyProductList.get(i).getSupplyInfoList();
                for (int j = 0; j < supplyInfoList.size(); j++) {
                    QueryWrapper qw2 = new QueryWrapper<>();
                    //规格
                    qw2.eq("pi_specs", supplyInfoList.get(j).getSpecs());
                    //商品名
                    qw2.eq("pi_productName", supplyProductList.get(i).getProductName());
                    //通过供货商品明细的 【规格】和【商品名】来查询相应的商品明细，进行库存添加
                    ProductInfoBean productInfo = productInfoMapper.selectOne(qw2);
                    if (productInfo != null) {
                        //修改库存明细里的库存数量
                        productInfo.setInventory(productInfo.getInventory() + supplyInfoList.get(j).getNum());
                        productInfoMapper.updateById(productInfo);
                        if (product.getStatus() != 0) {
                            //修改前端的商品库存和明细库存
                            webProductRemote.inKu(product.getProductName(), productInfo.getSpecs(), supplyInfoList.get(j).getNum());
                        }
                        //添加库存记录
                        InventoryRecordsBean jilu = new InventoryRecordsBean();
                        //设置库存记录的增加数量
                        jilu.setNum("+" + supplyProductList.get(i).getNum());
                        //设置库存记录的商品名【规格】
                        jilu.setProductName(supplyProductList.get(i).getProductName() + "【" + supplyInfoList.get(j).getSpecs() + "】");
                        iInventoryRecordsMapper.insert(jilu);
                        //修改 orderInfo 状态为 1-已入库
                        orderInfo.setOrderStatus(1);
                        orderInfoMapper.updateById(orderInfo);
                    } else {
                        //添加新的商品明细
                        SupplyInfoBean supplyInfo = supplyProductList.get(i).getSupplyInfoList().get(j);
                        productInfo = new ProductInfoBean();
                        //商品名
                        productInfo.setProductName(supplyProductList.get(i).getProductName());
                        productInfo.setProductId(product.getProductId());
                        //数量
                        productInfo.setInventory(supplyInfo.getNum());
                        //规格
                        productInfo.setSpecs(supplyInfo.getSpecs());
                        QueryWrapper queryWrapper2=new QueryWrapper<>();
                        queryWrapper2.eq("pk_siId",supplyInfo.getSiId());
                        SupplyInfoBean supplyInfoBean = supplyInfoMapper.selectOne(queryWrapper2);
                        //添加图片
                        productInfo.setImg(supplyInfoBean.getImgPath());

                        productInfoMapper.insert(productInfo);
                        //修改 orderInfo 状态为 1-已入库
                        orderInfo.setOrderStatus(1);
                        orderInfoMapper.updateById(orderInfo);

                        //添加库存记录
                        InventoryRecordsBean jilu = new InventoryRecordsBean();
                        //设置库存记录的增加数量
                        jilu.setNum("+" + supplyProductList.get(i).getNum());
                        //设置库存记录的商品名【规格】
                        jilu.setProductName(supplyProductList.get(i).getProductName() + "【" + supplyInfoList.get(j).getSpecs() + "】");
                        iInventoryRecordsMapper.insert(jilu);

                    }
                }
            }
            System.out.println("入库成功");
            //修改供应商供货批次表状态
            pscOrderInfoRemote.updateStatusByIdNum(idNum, 1);

            //根据主订单编号查询所有的批次，判断所有批次是否【已入库】，修改主订单的状态  orderInfo.getOrderIdNum()--主订单编号
            QueryWrapper<OrderInfoBean> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("fk_orderIdNum", orderInfo.getOrderIdNum());
            //得到该主订单的所有批次
            List<OrderInfoBean> orderInfoList = orderInfoMapper.selectList(queryWrapper);
            int totalNum = 0;
            for (OrderInfoBean oi : orderInfoList) {
                totalNum += oi.getGoodsNum();
            }
            //查询主订单
            QueryWrapper<SupplyBean> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("s_idNum", orderInfo.getOrderIdNum());
            SupplyBean supply = supplyMapper.selectOne(queryWrapper1);
            //如果 totalNum--每个批次商品数量的总和  和 主订单里的总数相同
            if (totalNum == supply.getTotalNum()) {
                //全部批次【已入库】，修改总订单状态为【已入库】
                supply.setOrderStatus(1);
                supplyMapper.updateById(supply);
            }
        } else {
            System.out.println("该批次已入库");
        }
    }

    @Override
    public void outKu(String productName, String specs, int num) {
        //修改product表
        QueryWrapper<ProductBean> qw = new QueryWrapper<>();
        qw.eq("p_productName", productName);
        ProductBean product = productMapper.selectOne(qw);
        product.setNum(product.getNum() - num);
        productMapper.updateById(product);
        //修改库存明细
        QueryWrapper<ProductInfoBean> qw2 = new QueryWrapper<>();
        qw2.eq("pi_specs", specs);
        //商品名
        qw2.eq("pi_productName", productName);
        ProductInfoBean productInfo = productInfoMapper.selectOne(qw2);
        productInfo.setInventory(productInfo.getInventory() - num);
        productInfoMapper.updateById(productInfo);
    }


}
